package com.ky.manage.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.ky.manage.R;
import com.ky.manage.activity.OrderListActivity;
import com.ky.manage.model.response.OrderResp;
import com.ky.manage.utils.ImageLoader.ImageLoaderUtils;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.ky.manage.utils.http.BusinessHttpReqUtils;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import androidx.annotation.NonNull;
import cz.msebera.android.httpclient.Header;

public class MyOrderAdapter extends BaseQuickAdapter<OrderResp.RowsDTO, BaseViewHolder> {

    List<OrderResp.RowsDTO> list;
    private Context context;
    Order2PayListner listner;

    public MyOrderAdapter(int layoutResId) {
        super(layoutResId);
    }

    public MyOrderAdapter(Context context, int layoutResId, List<OrderResp.RowsDTO> list, Order2PayListner listner) {
        super(layoutResId, list);
        this.list = list;
        this.context = context;
        this.listner = listner;
    }

    @Override
    protected void convert(@NonNull BaseViewHolder baseViewHolder, OrderResp.RowsDTO rowsDTO) {
        //ImageView imageView = baseViewHolder.findView(R.id.iv_order_goods_img);

        TextView price = baseViewHolder.findView(R.id.tv_goods_price);
        TextView count = baseViewHolder.findView(R.id.tv_goods_count);
        TextView netName = baseViewHolder.findView(R.id.tv_netPoint_name);
        TextView status = baseViewHolder.findView(R.id.tv_order_status);
        ListView listView = baseViewHolder.findView(R.id.lv_order_detail);
        TextView tvCancel = baseViewHolder.findView(R.id.tv_cancle_order);
        TextView tvToPay = baseViewHolder.findView(R.id.tv_to_pay);
        TextView tvTousu = baseViewHolder.findView(R.id.tv_tousu);
        TextView tvComment = baseViewHolder.findView(R.id.tv_comment);
        tvTousu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtils.showToast("功能研发中...");
            }
        });
        tvComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtils.showToast("功能研发中...");
            }
        });

        tvToPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String code = rowsDTO.getOrderCode();
                double price = rowsDTO.getGoodsPrice();
                reqToPay(code, price);
            }
        });

        if(rowsDTO.getNetPointName() != null)
            netName.setText(rowsDTO.getNetPointName().toString());

        View orderDone = baseViewHolder.findView(R.id.order_done);
        View orderNotDone = baseViewHolder.findView(R.id.order_not_done);
        switch (rowsDTO.getOrderStatus()) {
            case 2:
                orderNotDone.setVisibility(View.VISIBLE);
                break;
            case 1:
            case 4:
                orderDone.setVisibility(View.VISIBLE);
                break;
        }

        price.setText("总金额 ¥ " + rowsDTO.getGoodsPrice());
        count.setText(String.format(context.getResources().getString(R.string.goods_count), rowsDTO.getGoodsCount()));
        status.setText(OrderListActivity.getOrderStatus(rowsDTO.getOrderStatus()));
        listView.setAdapter(new PicAdapter(context, rowsDTO.getMountingsVoList()));
        //ImageLoaderUtils.loadImage(context, rowsDTO.get);
        setListViewHeightBasedOnChildren(listView);
    }

    private void reqToPay (String code, double price) {
        RequestParams params = new RequestParams();
        params.put("orderCode", code);
        params.put("price", price);

        AsyncHttpUtils.getInstance().get(BusinessHttpReqUtils.SERVICE_DOMAIN + "/appApi/createOrderPay", params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("lhm", "reqToPay onFailure = " + responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "reqToPay onSuccess = " + responseString);
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    if(jsonObject.has("code") && jsonObject.getInt("code") == 200) {
                        String msg = jsonObject.getString("msg");
                        if(listner!=null) {
                            listner.OnOrder2Pay(msg, code);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight =0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        System.out.println("aaa==="+totalHeight);
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public class PicAdapter extends BaseAdapter {
        Context context;
        List<OrderResp.RowsDTO.MountingsVoListDTO> list;

        public PicAdapter(Context context, List<OrderResp.RowsDTO.MountingsVoListDTO> data) {
            this.context = context;
            list = data;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_order_img, null);
            OrderResp.RowsDTO.MountingsVoListDTO mountings = list.get(position);
            ImageView img = convertView.findViewById(R.id.imv_order_img);
            if(mountings.getPicUrl() != null) {
                ImageLoaderUtils.loadImage(context, list.get(position).getPicUrl().toString(), img);
            }
            TextView goodsName = convertView.findViewById(R.id.tv_goods_name);
            TextView goodsPrice = convertView.findViewById(R.id.tv_goods_price);
            TextView goodsCount = convertView.findViewById(R.id.tv_goods_count);
            goodsName.setText(mountings.getMountingsName());
            goodsPrice.setText("¥ " + mountings.getUnitPrice());
            goodsCount.setText("x " + mountings.getAmount());
            return convertView;
        }
    }

    public interface Order2PayListner {
        void OnOrder2Pay(String qrCode, String orderCode);
    }
}
